package com.wlcb.jpower.chat.controller.push;

import com.alibaba.fastjson.JSONArray;
import com.wlcb.jpower.chat.reply.ReplyEntity;
import com.wlcb.jpower.chat.service.BaiduUnitService;
import com.wlcb.jpower.chat.service.customer.ChatService;
import com.wlcb.jpower.chat.service.customer.SpecialUserService;
import com.wlcb.jpower.module.base.enums.JpowerError;
import com.wlcb.jpower.module.base.exception.JpowerAssert;
import com.wlcb.jpower.module.base.vo.ResponseData;
import com.wlcb.jpower.module.common.controller.BaseController;
import com.wlcb.jpower.module.common.utils.ReturnJsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author: fei
 * @version: v1.0
 * @time: 2021/4/15 17:14
 * @desc: 百度unit接口
 */
@Api(tags = "发送百度unit")
@RestController
@RequestMapping("unit")
@AllArgsConstructor
public class UnitController extends BaseController {

    private BaiduUnitService unitService;
    private SpecialUserService specialUserService;
    private ChatService chatService;

    @PostMapping("query")
    @SneakyThrows(WxErrorException.class)
    public ResponseData<String> query(@ApiParam("appId") @RequestParam(required = false) String appId,
                                      @ApiParam("openid") @RequestParam(required = false) String openid,
                                      @ApiParam("unit话术") @RequestParam(required = false) String query) {

        JpowerAssert.notEmpty(appId, JpowerError.Arg,"appId不可为空");
        JpowerAssert.notEmpty(openid, JpowerError.Arg,"openid不可为空");
        JpowerAssert.notEmpty(query, JpowerError.Arg,"unit话术不可为空");

        if (specialUserService.findByOpenidAndAppid(openid, appId) == null) {
            return ReturnJsonUtil.fail("未开放该功能");
        }

        //强制结束当前会话
        chatService.forcedEnd(openid);

        String say = unitService.say(query, openid);
        ReplyEntity replyEntity = new ReplyEntity().kefu();
        replyEntity.setToUser(openid);
        replyEntity.setAppId(appId);
        List<ReplyEntity.ReplyBody> replyBodies = JSONArray.parseArray(say, ReplyEntity.ReplyBody.class);
        replyEntity.setReplyBodys(replyBodies);
        replyEntity.sendReply();
        return ReturnJsonUtil.ok("客服消息发送成功");
    }
}
